package com.asura.app.wechat.repository;

import android.os.SystemClock;

import com.asura.app.library.utils.ExecutorHelper;
import com.asura.app.wechat.repository.datasource.MomentDataSource;
import com.asura.app.wechat.repository.model.Tweet;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Single;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Asura on 2017/12/28.
 */

public class MomentDataRepository implements MomentDataSource {
    private List<Tweet> tweetsMemoryCache;
    private final MomentRemoteDataSource momentRemoteDataSource;

    public MomentDataRepository() {
        momentRemoteDataSource = new MomentRemoteDataSource();
    }

    @Override
    public Single<List<Tweet>> getTweets(String startId, int limit) {
        Single<List<Tweet>> tweetsSingle;
        if (tweetsMemoryCache != null) {
            tweetsSingle = Single.just(tweetsMemoryCache);
        } else {
            tweetsSingle = momentRemoteDataSource.getTweets(startId, limit)
                    .doOnSuccess(tweets -> tweetsMemoryCache = tweets);
        }
        return tweetsSingle.map(new Function<List<Tweet>, List<Tweet>>() {
            @Override
            public List<Tweet> apply(List<Tweet> tweets) throws Exception {
                int startPos = 0;
                //分页请求
                if (startId != null) {
                    for (int i = 0; i < tweets.size(); i++) {
                        if (tweets.get(i).getId().equals(startId)) {
                            startPos = i + 1;
                            break;
                        }
                    }
                    if (startPos == 0) startPos = tweets.size();
                }
                int endPos = Math.min(startPos + limit, tweets.size());
                List<Tweet> result = new ArrayList<>(endPos - startPos);
                for (int i = startPos; i < endPos; i++) {
                    result.add(tweets.get(i));
                }
                SystemClock.sleep(Math.round(Math.random()*2 + 1) * 1000);
                return result;
            }
        }).subscribeOn(Schedulers.from(ExecutorHelper.HIGH));
    }
}
